package pps.et5.eit.ex4;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.file.FileMessage;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.impl.DefaultCamelContext;

import pps.et5.eit.ex2.Service;

public class FournisseurService {
	//Vars
	private static ConnectionFactory connectionFactory;
	private static Connection connection;
	
	public ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}
	//Functions
	public float getPrix(String idProduit) {
		float f = (float) (100*Math.random());
		return f;
	}
	private void connect() throws Exception {
		// Initialise les attributs connectionFactory et destination.
		// Création d'un contexte JNDI
		InitialContext jndiContext = new InitialContext();
		// Lookup de la fabrique de connexion et de la destination
		connectionFactory = (ConnectionFactory) jndiContext.lookup("connectionFactory");
		//connection = connectionFactory.createConnection();
		//connection.start();
	}
	//elyes est gay
	public static void main(String[] args) { 
		try {
			final FournisseurService fournisseurservice = new FournisseurService();
			fournisseurservice.connect();
			System.out.println("Connection effectuée");
			CamelContext context = new DefaultCamelContext(); 
			context.addComponent("jms-test", JmsComponent.jmsComponentAutoAcknowledge(fournisseurservice.getConnectionFactory()));
			context.addRoutes(new RouteBuilder() {
				public void configure() throws Exception { 
					from("jms-test:fournisseur.requestQueue")

					.process(new Processor() {
						public void process(Exchange e) throws Exception {
							System.out.println("Demande de prix: id produit: "+e.getIn().getBody()); 
							e.getOut().setBody(String.valueOf(fournisseurservice.getPrix(e.getIn().getBody().toString())));
						}
					})
					.to("jms-test:fournisseur.responseQueue");
				}
			});
			context.start();
		} catch (Throwable t) { t.printStackTrace();
		} 

	}
}
